package com.chuanqi.admin.controller; 

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;

import com.chuanqi.admin.domain.Catalog;
import com.chuanqi.admin.dto.ZtreeNode;
import com.chuanqi.admin.qp.CatalogQp;
import com.chuanqi.admin.service.AdminCatalogService;
import com.chuanqi.common.utils.ServletUtils;



@Controller
@RequestMapping("/authc/catalog")
public class AdminCatalogController {
	@Autowired
	private AdminCatalogService catalogService;
	
	@RequestMapping(value="/create/{id}", method=RequestMethod.GET)
	public String createForm(@PathVariable("id") Long id, Model model){		
		System.out.println("pId="+id);
		Catalog parentCatalog = catalogService.getById(id);
		
		Catalog catalog = new Catalog();
		catalog.setParentId(parentCatalog.getId());
		catalog.setParentName(parentCatalog.getName());		
		
		model.addAttribute("catalog", catalog);
		model.addAttribute("action", "create");
		return "authc/catalog/form";
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("catalog") Catalog catalog, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
		if (bindingResult.hasErrors()) {
        	model.addAttribute("action", "create");        	
        	return "authc/catalog/form";
        }
                
		catalogService.insert(catalog);          
        redirectAttributes.addFlashAttribute("message", "添加目录成功！");
        return "redirect:/authc/catalog/list";       
    }
	
	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public String deleteById(@PathVariable Long id, RedirectAttributes redirectAttributes){
		catalogService.deleteById(id);
		redirectAttributes.addFlashAttribute("message", "删除目录成功！");
        return "redirect:/authc/catalog/list"; 
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {		
		Catalog catalog = catalogService.getById2(id);
		model.addAttribute("catalog", catalog );
		model.addAttribute("action", "update");
		return "authc/catalog/form";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("catalog") Catalog catalog, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
		if (result.hasErrors()) {
			model.addAttribute("action", "update");
			return "authc/catalog/form";
		}
		if (catalog != null) {
			catalogService.update(catalog);
			redirectAttributes.addFlashAttribute("message", "更新目录成功！");
		}
		
		return "redirect:/authc/catalog/list";
	}	
	
	@RequestMapping(value = "/getZtreeJson", method = RequestMethod.GET, produces="application/json")
    public @ResponseBody List<ZtreeNode> getZtreeJson(){
		List<ZtreeNode> ztreeNodeList = new ArrayList<ZtreeNode>();		
		List<Catalog> catalogList = catalogService.getAllCatalogList();
		for(Catalog catalog: catalogList){
			ZtreeNode ztreeNode = new ZtreeNode(catalog.getId(), catalog.getParentId(), catalog.getName(), true, false);
			ztreeNodeList.add(ztreeNode);
		}		
		
		return ztreeNodeList;
	}
    
	@RequestMapping(value = "/list", method=RequestMethod.GET)
	public String page(
			@RequestParam(value = "pageIndex", defaultValue = "1")  int pageIndex,
			@RequestParam(value = "pageSize",  defaultValue = "10") int pageSize,		
    		HttpServletRequest request,
    		Model model){
		
		String sortName = request.getParameter("sortName"); 		
		String sortOrder = request.getParameter("sortOrder");
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "ID";
			sortOrder = "ASC";
		}
		
		Map<String, Object> params = WebUtils.getParametersStartingWith(request, "q_"); 
				
		String name = (String)params.get("name");				
		String parentId = (String)params.get("parentId");  
		
		String searchParams = ServletUtils.parseParameterStringWithPrefix(params, "q_");
	
		long offset = pageIndex > 0 ? (pageIndex - 1) * pageSize : 0;
		CatalogQp qp = new CatalogQp();
		qp.setOffset(offset);
		qp.setPageSize(pageSize);
		qp.setName(name);
		qp.setParentId(parentId);	
		
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);			
		
		final long rowCount = catalogService.getCountByQueryBean(qp);				
		List<Catalog> catalogs = catalogService.getByQueryBean(qp);			    
	    
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }    
	    
	    long from = (pageIndex - 1) * pageSize + 1;
		long to = 0l;
		
		if(pageIndex<totalPages){			
			to = pageIndex * pageSize;
		}else{
			to = rowCount;
		}			
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
			model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);			
			model.addAttribute("searchParams", searchParams); 
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", from);
		    model.addAttribute("to", to);
		    
		    model.addAttribute("q_parentId", parentId);		    
		    
		    model.addAttribute("catalogs", catalogs);  
	    }     			
		
		return "authc/catalog/list";
	}
	
	
	@RequestMapping(value="/tree", method=RequestMethod.GET)
	public String tree(){
		return "authc/catalog/tree";
	}
	
	@RequestMapping(value="/test", method=RequestMethod.GET)
	public String createForm(){
		return "authc/catalog/test";
	}	
	
	
	
	@RequestMapping(value="/getCatalogListByName", method=RequestMethod.GET)
	public void getCatalogListByName(){
		String catalogName = "州";			
		
		List<Catalog> catalogList = catalogService.getCatalogListByName(catalogName);
		
		for(int i=0;i<catalogList.size();i++){
			Catalog catalog = catalogList.get(i);
			System.out.println("====id===="+catalog.getId());
			
			System.out.println("====parentId===="+catalog.getParentId());
		}		
	}
	
	@RequestMapping(value="/getCatalogListByPid", method=RequestMethod.GET)
	public String getCatalogListById(){
		//Long parentId = 2l;		
		String parentId = "2";
		List<Catalog> catalogList = catalogService.getCatalogListByPid(parentId);
		
		for(int i=0;i<catalogList.size();i++){
			Catalog catalog = catalogList.get(i);
			System.out.println("====id===="+catalog.getId());
			
			System.out.println("====parentId===="+catalog.getParentId());
		}		
		
		return "authc/catalog/tree";
	}
	
}
